import http.client
import json
import base64
import datetime

def encode_file_base64(file_path):
    with open(file_path,'rb') as f:
        return base64.b64encode(f.read()).decode('utf-8')
    
def decode_file_base64(base64string):
    base64data = base64string.encode('utf-8')
    filedata = base64.b64decode(base64data)
    x = datetime.datetime.now()
    dateTimeStr = x.strftime('%m-%d-%Y-%H-%M-%S')
    with open(f'{dateTimeStr}.mp4', "wb") as binary_file:
        binary_file.write(filedata)
    
def message_from_txt():
    message = {
        "prompt": "what is nba",
        "sys": "",
        "history": [],
    }
    json_data = json.dumps(message)
    return json_data
def message_from_image():
    image_path = './candy.jpg'
    imagedata = encode_file_base64(file_path=image_path)
    
    message = {
        "prompt": "explain this",
        "sys": "",
        "history": [],
        "image": imagedata,
        "imagetype":'jpg'
    }
    json_data = json.dumps(message)
    return json_data

def message_from_video():
    video_path = './video.mp4'
    data = encode_file_base64(file_path=video_path)
    # decode_file_base64(data)
    
    message = {
        "prompt": "These are the frames from the video.",
        "sys": "You are generating a video summary. Please provide a summary of the video. Respond in Markdown.",
        "history": [],
        "video": data,
    }
    json_data = json.dumps(message)
    return json_data
def message_from_audio():
    auido_path = './audio.wav'
    data = encode_file_base64(file_path=auido_path)
    # decode_file_base64(data)
    
    message = {
        "prompt": "The audio transcription is:{transcription}",
        "sys": "You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown.",
        "history": [],
        "audio": data,
    }
    json_data = json.dumps(message)
    return json_data
if __name__ == "__main__":
    conn = http.client.HTTPConnection('localhost:8088')

    headers = {'Content-type': 'application/json'}

    # json_data = message_from_txt()
    # json_data = message_from_image()
    # json_data = message_from_video()
    json_data = message_from_audio()
    # f = open("message.json", "a")
    # f.write(json_data)
    # f.close()

    conn.request('POST', '/post', json_data, headers)

    response = conn.getresponse()
    jstr = response.read().decode()


    json_object = json.loads(jstr)

    print(json_object['content'])
    print(json_object['history'])